<template>
  <div id="client">
    <el-container>
      <el-header height="40px" style='-webkit-app-region: drag'>
        <el-row style="margin-left: -20px;">
          <el-col :span='4' style="text-align: left;">
            <img width="36px" src="https://source.48.cn/mediasource/avatar/61730.jpg"/>
          </el-col>
          <el-col :span='17'>
            <span style="color: #aac913;"> PCMLive for 48g </span>
            <br/>
            <span style="font-size:10pt; color: #9f9f9f;"> by Splendor Jiang </span>
          </el-col>
          <el-col :span='3'>
            <i class="el-icon-minus" @click="minWindow" style='-webkit-app-region: no-drag;'></i>
            <i class="el-icon-close" @click="closeWindow" style='-webkit-app-region: no-drag; color: #ff0000;'></i>
          </el-col>
        </el-row>
      </el-header>
      <el-container>
        <el-aside id="aside" width='400px'>
          <el-row :gutter='0'>
            <el-col :span='12'>
              <el-cascader placeholder="空为选择全部" :options="options" v-model="selectedOptions" filterable clearable>
            </el-cascader>
            </el-col>
            <el-col :span='6'>
              <el-button id='btnTop' type='info' v-on:click='getMemberLive("0"); getMemberLiveRecord("0")'>获取直播</el-button>
            </el-col>
            <el-col :span='6'>
              <el-tooltip content='勾选则同时查询直播的人气值，显示在右下角，会减慢查询速度' placement='top'><el-checkbox v-model="autoRefresh" style="margin-top: 10px;">查询人气</el-checkbox></el-tooltip>
            </el-col>
          </el-row>
          <div id="divListSide">
            <div id='divlistLive'>
              ---当前直播数 {{listLive.length}} 总人气值 {{ onlineSum }} ---刷新时间 {{ this.formatDateTime(refreshTime) }}
                <div class="divListLiveItem" v-for='(item, index) in listLive' v-bind:key='index'>
                  <el-row :gutter='1'>
                    <el-col :span='4'>
                      <img v-for="n in item.coverPath.split(',').slice(0,1)" v-bind:key='n' width='50px' height="50px" style ="border-radius: 10px;" v-on:click="showPicMsgBox((n.indexOf('/') === 0) ? 'https://source.48.cn' + n : n)" v-bind:src="(n.indexOf('/') === 0) ? 'https://source.48.cn' + n : n"/>
                    </el-col>
                    <el-col :span='20'>
                      <el-row>
                        <el-col :span='9'>
                          <div><a href="javascript:void(0);" v-bind:style="{ color: getMember(parseInt(item.userInfo.userId)).team.color }" v-on:click="openExtUrl('https://www.weibo.com/' + getMember(parseInt(item.userInfo.userId)).all.wb_uid)"> {{ getMember(parseInt(item.userInfo.userId)).id !== 0 ? getMember(parseInt(item.userInfo.userId)).all.wb_name : item.title }} </a></div>
                        </el-col>
                        <el-col :span='2'>
                          <el-tooltip content='直播' placement='top'>
                            <i v-if='item.liveType === 1' class='el-icon-view'></i>
                          </el-tooltip>
                          <el-tooltip content='电台' placement='top'>
                            <i v-if='item.liveType === 2' class='el-icon-service'></i>
                          </el-tooltip>
                        </el-col>
                        <el-col :span='10'>
                          <div>{{ formatDateTime(parseInt(item.ctime)) }}</div>
                        </el-col>
                        <el-col :span='3'>
                          <img width="32px" v-bind:src="'https://source.48.cn' + getMember(parseInt(item.userInfo.userId)).team.all.logo2"/>
                        </el-col>
                      </el-row>
                      <el-row>
                        <el-col :span='22' style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis;">
                          <a class="titleLive" href="javascript:void(0);" v-on:click='showPlay(item, true)'>{{ item.title }}</a>
                        </el-col>
                        <el-col :span="2">
                          {{ index + 1 }}
                        </el-col>
                      </el-row>
                      <el-row style="text-align: right;">
                          <el-col :span="20">
                            <img height="15px" style ="border-radius: 10px;" @click="showPicMsgBox('https://source.48.cn' + item.userInfo.avatar)" v-bind:src="'https://source.48.cn' + item.userInfo.avatar" />
                          </el-col>
                          <el-col :span="4">
                            <span style="color: #0000ae; font-size:10px;">{{item.number}} </span>
                          </el-col>
                        </el-row>
                    </el-col>
                  </el-row>
              </div>
              <div style="text-align: center;"><el-button style="justify-content: center;" v-if='nextLive !== "0"' @click="getMemberLive(nextLive)" icon="el-icon-arrow-down" size="mini"> </el-button></div>
            </div>
            <div id='divlistReview'>
              ---默认只显示前20个录播 后面可下拉  ---{{ numberSumShow }}
                <div class="divListItem" v-for='(item, index) in listReview' v-bind:key='item.liveId'>
                  <el-row :gutter='0'>
                    <el-col :span='4'>
                      <img v-for="n in item.coverPath.split(',').slice(0,1)" v-bind:key='n' width='50px' height="50px" style ="border-radius: 10px;" v-on:click="showPicMsgBox((n.indexOf('/') === 0) ? 'https://source.48.cn' + n : n)" v-bind:src="(n.indexOf('/') === 0) ? 'https://source.48.cn' + n : n"/>
                    </el-col>
                    <el-col :span='20'>
                      <el-row>
                        <el-col :span='9'>
                          <div><a href="javascript:void(0);" v-bind:style="{ color: getMember(parseInt(item.userInfo.userId)).team.color }" v-on:click="openExtUrl('https://www.weibo.com/' + getMember(parseInt(item.userInfo.userId)).all.wb_uid)"> {{ getMember(parseInt(item.userInfo.userId)).id !== 0 ? getMember(parseInt(item.userInfo.userId)).all.wb_name : item.title.replace('（回放生成中）', '') }} </a></div>
                        </el-col>
                        <el-col :span='2'>
                          <el-tooltip content='直播' placement='top'>
                            <i v-if='item.liveType === 1' class='el-icon-view'></i>
                          </el-tooltip>
                          <el-tooltip content='电台' placement='top'>
                            <i v-if='item.liveType === 2' class='el-icon-service'></i>
                          </el-tooltip>
                        </el-col>
                        <el-col :span='10'>
                          <div>{{ formatDateTime(parseInt(item.ctime)) }}</div>
                        </el-col>
                        <el-col :span='3'>
                          <img width="32px" v-bind:src="'https://source.48.cn' + getMember(parseInt(item.userInfo.userId)).team.all.logo2"/>
                        </el-col>
                      </el-row>
                      <el-row>
                        <el-col :span='22' style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis;">
                          <a class="titleLive" href="javascript:void(0);" v-on:click='showPlay(item, false)'><span>{{ item.title }}</span></a>
                        </el-col>
                        <el-col :span="2">
                          <span>{{ index + 1 }} </span>
                        </el-col>
                      </el-row>
                      <el-row style="text-align: right;">
                        <el-col :span="20">
                          <img height="15px" style ="border-radius: 10px;" @click="showPicMsgBox('https://source.48.cn' + item.userInfo.avatar)" v-bind:src="'https://source.48.cn' + item.userInfo.avatar" />
                        </el-col>
                        <el-col :span="4">
                          <span style="color: #00ab00; font-size:10px;">{{item.number}} </span>
                        </el-col>
                      </el-row>
                    </el-col>
                  </el-row>
                </div>
                <div style="text-align: center;"><el-button v-if='nextRecord !== "0"' @click="getMemberLiveRecord(nextRecord)" icon="el-icon-arrow-down" size="mini"> </el-button></div>
              </div>
          </div>
        </el-aside>

      </el-container>
    </el-container>
  </div>
</template>

<script>
import PlayVideo from '../components/PlayVideo.vue'
// import SystemInformation from './LandingPage/SystemInformation.vue'
import Danmaku from '../components/Danmaku.vue'
import '../../api/NIM_Web_SDK_v5.4.0.js'
import '../../api/NIM_Web_NIM_v5.4.0.js'
import '../../api/NIM_Web_Chatroom_v5.4.0.js'
import { remote } from 'electron'

export default {
  name: 'landing-page',
  components: { PlayVideo, Danmaku },
  data () {
    return {
      message: '',
      list: [],
      listShow: [],
      timeCurrent: 0,
      listReview: [],
      listLive: [],
      options: [],
      selectedOptions: [],
      onlineSum: 0,
      refreshTime: 0,
      currentLiveRoomid: -1,
      autoRefresh: false,
      numberSum: 0,
      numberSumShow: '',
      mapReviewDetail: new Map(),
      isPlay: false,
      memberInfo: '',
      nextLive: '0',
      nextRecord: '0'
    }
  },
  methods: {
    formatDateTime (inputTime) {
      var date = new Date(inputTime)
      var y = date.getFullYear()
      var m = date.getMonth() + 1
      m = m < 10 ? '0' + m : m
      var d = date.getDate()
      d = d < 10 ? '0' + d : d
      var h = date.getHours()
      h = h < 10 ? '0' + h : h
      var minute = date.getMinutes()
      var second = date.getSeconds()
      minute = minute < 10 ? '0' + minute : minute
      second = second < 10 ? '0' + second : second
      return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second
    },
    openExtUrl (sUrl) {
      this.$electron.shell.openExternal(sUrl)
    },
    getMember (memberId) {
      return (new this.$Member(memberId))
    },
    getDanmakuTimeStr (sec) {
      return this.$myutil.getDanmakuTimeStr(sec)
    },
    randomString (l) {
      var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz012345678_@'
      var password = ''
      for (let i = 0; i < l; i++) {
        password += chars.substr(Math.round(Math.random() * chars.length), 1)
      }
      return password
    },
    getToken () { // 获取直播聊天室token用,目前未使用
      var request = require('request')
      var cv = this.randomString(8)
      var tt = Math.round(new Date().getTime() / 1000)
      console.log(cv)
      var options = {
        method: 'POST',
        json: true,
        url: 'http://zhibo.ckg48.com/Server/do_ajax_setcookie',
        headers: {
          'Content-Type': 'application/json',
          'version': '5.0.1',
          'os': 'Android'
        },
        qs: {
          timestamp: tt,
          cookie_val: cv,
          type: 2
        }
      }
      request(options, function (err, res, body) {
        console.info(res)
        console.log(err)
        console.log(res.body)
      })
      request(options, function (err, res, body) {
        console.info(res)
        console.log(err)
        console.log(res.body)
      })
    },
    showPicMsgBox (urlPic) {
      const h = this.$createElement
      this.$msgbox({
        title: '封面图查看',
        message: h('p', null, [
          h('img', { attrs: {src: urlPic}, style: 'maxHeight: 540px; maxWidth: 360px;' }, null),
          h('span', { style: 'size: 10px; word-break:normal; width:auto; display:block; white-space: pre-wrap; word-wrap: break-word; overflow: hidden;' }, urlPic)
        ]),
        confirmButtonText: '下载图片',
        showCancelButton: true,
        cancelButtonText: '关闭',
        center: true
      }).then(action => {
        this.downloadPic(urlPic)
      }).catch(() => {

      })
    },
    downloadPic (urlPic) {
      var request = require('request')
      var fs = require('fs')
      if (urlPic) {
        const file = remote.dialog.showSaveDialog(remote.getCurrentWindow(), {
          filters: [
            {name: 'Image Files', extensions: ['jpg', 'jpeg', 'png', 'bmp']},
            {name: 'All Files', extensions: ['*']}]
        })
        if (file) {
          request(urlPic).pipe(fs.createWriteStream(file))
          this.$message({
            type: 'success',
            message: '图片已保存至' + file
          })
        }
      }
    },
    getMemberLive (next) {
      var v = this
      v.onlineSum = 0
      v.refreshTime = new Date().getTime()

      var request = require('request')
      var options = {
        method: 'POST',
        json: true,
        url: 'https://pocketapi.48.cn/live/api/v1/live/getLiveList',
        headers: {
          'Accept': 'application/json, text/javascript, */*; q=0.01',
          'Content-Type': 'application/json; charset=UTF-8',
          'Origin': 'null',
          'Sec-Fetch-Mode': 'cors',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3800.0'
        },
        body: {
          groupId: '0',
          next: v.next,
          record: 'false',
          teamId: '0',
          userId: '0'
        }
      }
      request(options, function (err, res, body) {
        console.info(res.body)
        console.log(err)
        if (next !== '0') {
          v.listLive = v.listLive.concat(res.body.content.liveList)
        } else {
          v.listLive = res.body.content.liveList
        }
        if (res.body.content.next === next) {
          v.nextLive = '0'
        } else {
          v.nextLive = res.body.content.next
        }
        // for (let i = 0; i < v.listLive.length; i++) {
        //   v.getAllLiveOnline(i, v.listLive[i].roomId)
        // }
        if (v.autoRefresh) {
          for (let i = 0; i < v.listLive.length; i++) {
            v.getLiveOne(i, v.listLive[i].liveId) // 直播则每次都去获取人气值
          }

          // if (!v.mapReviewDetail.has(v.listLive[i].liveId)) {
          //   v.getLiveOne(i, v.listLive[i].liveId)
          // } else {
          //   let itemMap = v.mapReviewDetail.get(v.listLive[i].liveId)
          //   v.listReview[i].number = itemMap.number
          //   v.onlineSum += v.listReview[i].number
          // }
        }
      })
    },
    getMemberLiveRecord (next) {
      var v = this
      v.numberSum = 0

      var request = require('request')
      var options = {
        method: 'POST',
        json: true,
        url: 'https://pocketapi.48.cn/live/api/v1/live/getLiveList',
        headers: {
          'Accept': 'application/json, text/javascript, */*; q=0.01',
          'Content-Type': 'application/json; charset=UTF-8',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3800.0'
        },
        body: {
          groupId: '0',
          next: next,
          record: 'true',
          teamId: '0',
          userId: v.selectedOptions.length > 2 ? v.selectedOptions[2] : 0
        }
      }
      request(options, function (err, res, body) {
        console.info(res.body)
        console.log(err)
        let lastn = 0
        if (next !== '0') {
          lastn = v.listReview.length
          v.listReview = v.listReview.concat(res.body.content.liveList)
        } else {
          v.listReview = res.body.content.liveList
        }
        if (res.body.content.next === next) {
          v.nextRecord = '0'
        } else {
          v.nextRecord = res.body.content.next
        }

        for (let i = lastn; i < v.listReview.length; i++) {
          if (!v.mapReviewDetail.has(v.listReview[i].liveId)) {
            if (v.autoRefresh) {
              v.getLiveOneRecord(i, v.listReview[i].liveId)
            }
          } else {
            let itemMap = v.mapReviewDetail.get(v.listReview[i].liveId)
            v.listReview[i].number = itemMap.number
            v.numberSum += v.listReview[i].number
            v.numberSumShow = '录播数' + v.listReview.length + '总人气值:' + v.numberSum
          }
        }
      })
    },
    getLiveOne (index, liveId) {
      var v = this
      var request = require('request')
      var options = {
        method: 'POST',
        json: true,
        url: 'https://pocketapi.48.cn/live/api/v1/live/getLiveOne',
        headers: {
          'Content-Type': 'application/json; charset=UTF-8',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3800.0'
        },
        body: {
          liveId: liveId
        }
      }
      request(options, function (err, res, body) {
        // console.info(res.body)
        console.log(err)
        v.listLive[index].number = res.body.content.onlineNum
        v.mapReviewDetail.set(v.listLive[index].liveId, v.listLive[index])
        v.onlineSum += v.listLive[index].number
      })
    },
    getLiveOneRecord (index, liveId) {
      var v = this
      var request = require('request')
      var options = {
        method: 'POST',
        json: true,
        url: 'https://pocketapi.48.cn/live/api/v1/live/getLiveOne',
        headers: {
          'Content-Type': 'application/json; charset=UTF-8',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3800.0'
        },
        body: {
          liveId: liveId
        }
      }
      request(options, function (err, res, body) {
        // console.info(res.body)
        console.log(err)
        v.listReview[index].number = res.body.content.onlineNum
        v.mapReviewDetail.set(v.listReview[index].liveId, v.listReview[index])
        v.numberSum += v.listReview[index].number
        v.numberSumShow = '录播数' + v.listReview.length + '总人气值:' + v.numberSum
      })
    },
    minWindow () {
      const ipc = require('electron').ipcRenderer
      ipc.send('window-min')
    },
    closeWindow () {
      const ipc = require('electron').ipcRenderer
      ipc.send('window-close')
    },
    showPlay (liveItem, isLive) {
      var v = this
      var request = require('request')
      var options = {
        method: 'POST',
        json: true,
        url: 'https://pocketapi.48.cn/live/api/v1/live/getLiveOne',
        headers: {
          'Content-Type': 'application/json; charset=UTF-8',
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3800.0'
        },
        body: {
          liveId: liveItem.liveId
        }
      }
      request(options, function (err, res, body) {
        console.info(res.body)
        console.log(err)
        v.showUrl(res.body.content, isLive, liveItem)
      })
    },
    showUrl (url, isLive, liveItem) {
      // this.message = url.title
      let routeData = this.$router.resolve({ path: '/playvideo',
        query: {
          streamPath: url.playStreamPath,
          isLive: isLive,
          title: url.user.userName + ' ' + url.roomId,
          startTime: this.formatDateTime(parseInt(liveItem.ctime)),
          number: url.onlineNum
        }
      })
      // resizable=true, menubar=no, scrollbars=no
      window.open(routeData.href, url.user.userName + ' ' + url.roomId, 'width=301, height=570, resizable=true, top=100px, left=516px')

      let routeDataDanmaku = this.$router.resolve({ path: '/danmaku',
        query: {
          isLive: isLive,
          roomId: url.roomId,
          liveId: url.liveId,
          lrcPath: url.msgFilePath,
          number: isLive ? url.onlinecount : url.onlineNum,
          startTime: parseInt(liveItem.ctime),
          title: url.user.userName + ' ' + url.roomId
        }
      })
      window.open(routeDataDanmaku.href, url.liveId, 'width=300, height=528, resizable=true, top=100px, left=816px')
      if (isLive) {
        this.currentLiveRoomid = url.roomId
      } else {

      }
      this.isPlay = true
    }
  },
  mounted: function () {
    // 加载完毕后读取一次全部成员数据
    var v = this
    for (let g of v.$groups) {
      let lvl2 = []
      for (let t of g.teams) {
        let lvl3 = []
        for (let m of t.members()) {
          let lvl3item = {value: m.id, label: m.name}
          lvl3.push(lvl3item)
        }
        let lvl2item = {value: t.id, label: t.fullname, children: lvl3}
        lvl2.push(lvl2item)
      }
      let lvl1item = {value: g.id, label: g.name, children: lvl2}
      v.options.push(lvl1item)
    }
  }
}
</script>

<style scoped>
#divListSide {
  overflow-x: auto;
  overflow-y: auto;
  width: 400px;
  height: 580px;
}
#divlistReview {
  font-size: 12px;
}
#divlistLive {
  font-size: 12px;
}
#user {
  color: skyblue;
}
#text {
  color: wheat;
}
#time {
  color: blanchedalmond;
  background-color: blueviolet;
  opacity: 0.4;
}
.el-header,
.el-footer {
  background-color: #fefeff;
  color: #333;
  text-align: center;
  margin: 0px;
}

.el-aside {
  background-color: #ffffff;
  color: #333;
}

body > .el-container {
  margin-bottom: 0px;
}

body {
  margin: 0px;
}

#client {
  margin: 0px;
  background-color: #fefeff;
}
.divListLiveItem {
  background-color: rgb(213, 247, 146);
  margin: 5px;
  border-radius: 10px;
  height: 54px;
}
.divListItem {
  background-color:rgb(245, 225, 243);
  margin: 5px;
  border-radius: 10px;
  height: 54px;
}

.titleLive {
  color: #5959fa;
  font-size: 12px;
}
</style>

